<template>
  <div class="home">
    <div id="cesium-container"></div>
    <div class="header">
      <div class="title">{{ systemName }}</div>
      <div class="header-bg">
        <img src="../../assets/home/head/header-bg.png" alt="" />
      </div>
      <div class="user-info-item">
        <!-- <span>当前用户：{{ currentUser }}</span> -->
        <!-- <img class="quitBtn" src='../../assets/quit.png' />
        <img @click="changePassword"/> -->
        <!-- trigger="click" -->
          <el-dropdown  @command="handleCommand">
            <span class="el-dropdown-link">
              当前用户：{{ currentUser }}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command='goUserManager' icon="el-icon-edit-outline">用户管理</el-dropdown-item>
              <el-dropdown-item command='goInterface' icon="el-icon-edit-outline">接口共享</el-dropdown-item>
              <el-dropdown-item command='logout' icon="el-icon-switch-button">退出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

      </div>
    </div>
    <div class="content">
      <Left></Left>
      <Bottom></Bottom>
      <Right></Right>
    </div>
  </div>
</template>
<script>
import cookies from "@/utils/cookies";
import Right from "@/views/right/index.vue";
import Left from "@/views/left/index.vue";
import Bottom from "@/views/bottom/index.vue";
import * as turf from "@turf/turf";
import * as homeApi from "@/api/home.js";
import { logout } from "@/api/user.js";

const Cesium = window.Cesium;

export default {
  props: {},
  components: {
    Right,
    Left,
    Bottom,
  },
  data() {
    return {
      systemName: "", // 
      currentUser: "",
      // viewer: null,
      form: {
        username: "",
        password: "",
        captcha: "",
      },

      // gis 临时数据
      gisdata_road: [],
      gisdata_building: [],
    };
  },
  mounted() {

    if(process.env.NODE_ENV === 'production') {
      // 临湘市乡村地名大数据系统
      this.systemName = '乡村地名二三维一体化平台';
    } else {
      this.systemName = '';
    }
    // event.stopPropagation();
    this.currentUser = cookies.getCookies("current_user");
    this.intiMap();
    this.initMapEvent();
    this.initGisData();
    // this.apiTest();
  },
  methods: {
    intiMap() {
      // Cesium.Ion.defaultAccessToken =
      //   "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmZTE3ZTUzMi1mNjFhLTQzYzgtOWU3NS1jNjUzNTljYjNhYzEiLCJpZCI6ODg4MDksImlhdCI6MTY0OTQwODQ5NH0.FXnJga6OYyHyKW33-2iPY_U0JuASH8_3DUWhyy43_Q0";
      window.cesiumViewer = new Cesium.Viewer("cesium-container", {
        animation: false, // 左下角动画控件圆盘
        timeline: false, // 底部时间栏
        fullscreenButton: false,
        homeButton: false,
        geocoder: false,
        animation: false, // 隐藏掉时钟 图中6
        navigationHelpButton: false, // 隐藏帮助按钮
        sceneModePicker: false, // 隐藏切换二三维按钮
        baseLayerPicker: false, // 隐藏切换底图按钮
        imageryProvider: false,
        infoBox: false,
        selectionIndicator: false, // 当选择标签时不出现选中样式
        creditContainer: document.createElement("div"),
      });
      // this.$store.commit("setViewer", window.cesiumViewer);
      window.cesiumViewer.scene.globe.depthTestAgainstTerrain = true;

      window.cesiumViewer.imageryLayers.addImageryProvider(
        new Cesium.WebMapTileServiceImageryProvider({
          url: "http://t0.tianditu.gov.cn/img_w/wmts?tk=34b8e64ba50c6ed5e726b1f7eef9839a",
          layer: "img",
          style: "default",
          tileMatrixSetID: "w",
          format: "tiles",
          maximumLevel: 18,
        })
      );
      window.cesiumViewer.imageryLayers.addImageryProvider(
        new Cesium.WebMapTileServiceImageryProvider({
          url: "http://t0.tianditu.gov.cn/cia_w/wmts?tk=34b8e64ba50c6ed5e726b1f7eef9839a",
          layer: "cia",
          style: "default",
          tileMatrixSetID: "w",
          format: "tiles",
          maximumLevel: 18,
        })
      );
    },

    initMapEvent() {
      const handler = new Cesium.ScreenSpaceEventHandler(
        window.cesiumViewer.scene.canvas
      );
      handler.setInputAction((event) => {
        console.log("left click map event...");
        this.showMousePosition(event.position);
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },

    initGisData() {
      const tiles3dUrl = process.env.NODE_ENV === 'production'?'http://81.70.192.7:81/lx_3dtiles/tileset.json':"http://localhost/lx_3dtiles/tileset.json";
      // this.laodTileset('tileset', tiles3dUrl)
      this.loadGisData();

      window.cesiumViewer.camera.flyTo({
        destination: new Cesium.Cartesian3(
          -2214813.8928321428,
          5105972.913576545,
          3124649.0239411164
        ),
        orientation: {
          heading: 6.283185307179581,
          pitch: -1.5689605746660948,
          roll: 0,
        },
      });
    },

    loadGisData() {
      console.log("load gis data...");
    },

    laodTileset(id, url) {
      const tileset = new Cesium.Cesium3DTileset({
        skipLevelOfDetail: true,
        baseScreenSpaceError: 1024,
        maximumScreenSpaceError: 64, // 数值加大，能让最终成像变模糊
        skipScreenSpaceErrorFactor: 16,
        skipLevels: 1,
        immediatelyLoadDesiredLevelOfDetail: false,
        loadSiblings: true, // 如果为true则不会在已加载完概况房屋后，自动从中心开始超清化房屋
        cullWithChildrenBounds: true,
        cullRequestsWhileMoving: true,
        cullRequestsWhileMovingMultiplier: 10, // 值越小能够更快的剔除
        preloadWhenHidden: true,
        preferLeaves: true,
        maximumMemoryUsage: 512, // 内存分配变小有利于倾斜摄影数据回收，提升性能体验
        progressiveResolutionHeightFraction: 0.5, // 数值偏于0能够让初始加载变得模糊
        // dynamicScreenSpaceErrorDensity: 0.1, // 数值加大，能让周边加载变快
        dynamicScreenSpaceErrorDensity: 1, // 数值加大，能让周边加载变快
        dynamicScreenSpaceErrorFactor: 1, // 不知道起了什么作用没，反正放着吧先
        dynamicScreenSpaceError: true, // 根据测试，有了这个后，会在真正的全屏加载完之后才清晰化房屋

        url,
      });
      tileset.readyPromise.then(() => {
        window.cesiumViewer.scene.primitives.add(tileset);
        window.cesiumViewer.flyTo(tileset);
      });
    },

    /**
     * 输出鼠标位置
     * @param {*} position
     */
    showMousePosition(position) {
      const screenPosition = position;
      // 拾取对象
      // viewer.scene.pick(event.position)

      // 有地形的情况下误差较大，在使用时需要关闭深度测试
      // let position = viewer.scene.camera.pickEllipsoid(event.position, viewer.scene.globe.ellipsoid);

      // 一定开启深度检测（viewer.scene.globe.depthTestAgainstTerrain = true），否则在没有没有3dTile模型的情况下，会出现空间坐标不准的问题
      let pickedPosition =
        window.cesiumViewer.scene.pickPosition(screenPosition);
      if (!pickedPosition) {
        // 最好开启深度检测
        const ray = window.cesiumViewer.camera.getPickRay(screenPosition); // 获取一条射线
        const position = window.cesiumViewer.scene.globe.pick(
          ray,
          window.cesiumViewer.scene
        );
        if (!position) return;
        pickedPosition = position;
      }

      const cartographic = Cesium.Cartographic.fromCartesian(pickedPosition);
      console.log(pickedPosition, cartographic);
      const longtitude = Cesium.Math.toDegrees(cartographic.longitude);
      const latitude = Cesium.Math.toDegrees(cartographic.latitude);
      console.log(`${longtitude},${latitude}`);

      console.log(window.cesiumViewer.camera);
    },

    handleCommand (command) {
      if (command === 'logout') {
        this.logout()
      } else if (command === 'goUserManager') {
        this.$router.push('/user')
      } else if (command === 'goInterface') {
        this.$router.push('/interface')
      }
    },
    // 注销，登出
    async logout() {
      // await this.$store.dispatch('user/logout')
      logout().then(() => {
        cookies.removeToken();
        cookies.removeCookies("current_user");
        this.$router.push(`/login?redirect=${this.$route.fullPath}`);
      });
    },

    // 接口测试
    apiTest() {
      // homeApi.getSelectList().then(result => console.log(result));
      // homeApi.getAddressList({page:1,pageSize:10,daima:'12100'}).then(result => console.log(result));
      // homeApi.getAddressDalei().then(result => console.log(result));
      // homeApi.getAddressZhonglei({parentCode:'12000'}).then(result => console.log(result));
      // homeApi.getAddressXiaolei({parentCode:'12100'}).then(result => console.log(result));
      // homeApi.getFields({daima: '12100'}).then(result => console.log(result));
      // homeApi.getDoorplateList({ page: 1, pageSize: 10 }).then(result => console.log(result))
      // homeApi.getScenicpotList({ page: 1, pageSize: 10 }).then(result => console.log(result));
      // homeApi.getDeliveryList({ page: 1, pageSize: 10 }).then((result) => console.log(result));
      // homeApi.findAllBuildings().then((result) => console.log(result));
      // const startTime = (new Date()).getTime();
      // homeApi.getAddressAll().then((result) => {
      //   // console.log(result)
      //   const data = JSON.parse(result.data);
      //   const features = [];
      //   data.map(item => {
      //     const properties = item;
      //     const feature = {
      //       "type": "Feature",
      //       "properties": item,
      //       "geometry": {
      //         "type": "Point",
      //         "coordinates": [Number(item.DongJing)/10000,Number(item.BeiWei)/10000]
      //       }
      //     }
      //     features.push(feature);
      //   })
      //   const featureCollection = {
      //     "type": "FeatureCollection",
      //     "features": features
      //   };
      //   console.log(featureCollection);
      //   const endTime = (new Date()).getTime();
      //   console.log(endTime - startTime);
      // });
    },
  },
};
</script>
<style lang="less" scope>
.home {
  width: 100%;
  height: 100%;
  position: relative;
  #cesium-container {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
  .header {
    // pointer-events: none;
    position: fixed;
    z-index: 2;
    top: 0;
    left: 0;
    width: 100%;
    height: 88px;
    background: linear-gradient(180deg, #01457b 0%, rgba(8, 25, 38, 0) 100%);

    //  .header-bg {
    //         position: absolute;
    //         top: 0;
    //         left: 0;
    //         width: 100%;
    //         height: 88px;
    //         background: linear-gradient(
    //           180deg,
    //           #01457b 0%,
    //           rgba(8, 25, 38, 0) 100%
    //         );
    //       }
    img {
      width: 100%;
      height: 100%;
    }
    .title {
      position: absolute;
      z-index: 10;
      height: 44px;
      line-height: 44px;
      top: 40%;
      left: 50%;
      transform: translate(-50%, -50%);
      text-align: center;
      text-shadow: 0px 0px 4px #cacaca;
      font-family: PangMenZhengDao;
      font-size: 30px;
      font-weight: 400;
      letter-spacing: 2.72px;
      background: linear-gradient(180deg, #c4daea 0%, #fff 53.2%, #fff 100%);
      background-clip: text;
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }

    .user-info-item {
      position: absolute;
      right: 20px;
      top: -15px;
      line-height: 80px;
      width: 155px;
      // color:white;
      // cursor: pointer;

      span {
        font-size: 16px;
      }

      .el-dropdown-link {
        cursor: pointer;
        color: white;
      }
    }
  }
  .content {
    width: 100%;
    height: 100%;
    // background-color: #ccc;
    pointer-events: none;
    position: relative;
  }
}
</style>
